define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'store/housein/index',
                    add_url: 'store/housein/add',
                    multi_url: 'store/housein/multi',
                    table: 'house_in',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                searchFormVisible: true,
                searchFormTemplate: 'customformtpl',

                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'order_id', title: "入库单号"},
                        {field: 'type', title: __('Type'), searchList: {"1":"采购入库","2":"要货入库","3":"退货入库","4":"代理商退货回总部","5":"调拔入库","6":"盘盈","7":"其他"}, formatter: Table.api.formatter.normal},
                        {field: 'cid', title: __('Cid')},

                        {field: 'inputtime', title: __('Inputtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'publisher', title: __('Publisher')},
                        {
                            field: 'operate',
                            width: "120px",
                            title: '查看订单',
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    title: __('查看订单'),
                                    text: __('查看订单'),
                                    classname: 'btn btn-primary btn-success btn-detail btn-dialog',
                                    icon: 'fa fa-camera',
                                    url: 'store/housein/view',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var index = $("#ultable").attr("data-listidx");
            layer.load("加载中");
            setTimeout(function() {//异步处理，防止冒泡事件，select未加载成功
                layer.closeAll();
                $(".btn-append").click(function () {

                    var str='<tr id="tr'+index+'"><td>1</td><td ><input  data-id="'+index+'"  data-rule="required"  style="width:200px" id="sele'+index+'" data-source="ajax/shops"  data-field="cname" data-primary-key="id" name="shop['+index+'][id]"  class="form-control selectpage wuji" style="width:100%" placeholder="请选择商品"  type="text" value="" autocomplete="off"></td>';

                    str+='<td style="text-align: left; vertical-align: middle; " width="200">\n' +
                        '\n' +
                        '\n' +
                        '\n' +
                        '    <div class="operate" data-id="20" data-name="ask">\n' +
                        '\n' +
                        '\n' +
                        '        <span class="btn-group open">\n' +
                        '                <a href="javascript:;" class="btn btn-xs btn-primary btn-success btn-install" data-type="price" data-donateimage="https://cdn.fastadmin.net/uploads/donate/karson.png" data-version="1.0.1"> 半成品</a>\n' +
                        '                <a class="btn btn-xs btn-success dropdown-toggle" data-toggle="dropdown" href="javascript:;" aria-expanded="true">\n' +
                        '                    <span class="fa fa-caret-down"></span>\n' +
                        '                </a>\n' +
                        '                <ul class="dropdown-menu" id="zifen'+index+'">\n' +
                        '                </ul>\n' +
                        '            </span>\n' +
                        '        </div></td>';
                    str+='<td id="sl'+index+'">&nbsp;</td><td id="sc'+index+'"><a data-id="'+index+'" style="cursor: pointer" class="del btn btn-xs btn-success btn-editone"><i class="fa fa-trash"></i></a></td>';
                    str+='</tr>';


                    $("#ultable").append(str);
                    $("#sele"+index).selectPage({
                        params:{'rows':index},
                        eAjaxSuccess: function (data) {
                            data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                            data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                            return data;
                        },
                        dropButton : false,

                        eSelect : function(data) {

                            var ind = this.params.rows;//当前行数
                            /* var wuji = $('.wuji');
                             if (wuji.length > 1) {
                                 var j = 0;//查看当前值出现的次数，如果 》 1则重复了。
                                 for (var i = 0; i < wuji.length; i++) {
                                     var did = wuji.eq(i).data('id');
                                     if ($("#sele" + did).val() == data.id) {
                                         j++;
                                     }
                                 }
                                 if (j > 1) {
                                     layer.alert("不能重复选择" + data.cname);
                                     $("#sele" + ind).selectPageClear();
                                     return;
                                 }
                             }
                             var dselects = $("#ultable").attr("data-selects");
                             if (dselects == '') {
                                 $("#ultable").attr("data-selects", data.id);
                             } else {

                                $("#ultable").attr("data-selects", dselects + ',' + data.id);
                             }*/
                            // $("#sele"+ind).selectPageClear();
                            $("#bh"+ind).html(data.b_n);
                            var st='';
                            for (var i=0;i<data.zifenlei.length;i++){
                               st+='<li><a href="javascript:;" class="btn-install">'+data.zifenlei[i]["cname"]+'</a></li>';
                            }
                            $("#zifen"+ind).html(st);
                            $("#fl"+ind).html(data.className);
                            $("#sl"+ind).html('<input type="text"  data-rule="required"  autocomplete="off" value="1" placeholder="1" class="form-control form-num zzwselect" name="shop['+ind+'][num]"> ');
                            $("#sl"+ind).find('input').focus();
                            plus();
                        }







                    });

                    table_sort();
                    index++;
                });
            },500);
            $("#ultable").on("click",".del",function(){
                var ind = $(this).attr('data-id');
                $("#sele"+ind).selectPageClear();
                $("#tr"+ind).remove();
                table_sort();
            });

            $("#ultable").on("keyup",".form-num",function(){
                plus();
            });
            $("#ultable").on("keyup",".form-price",function(){
                plus();
            });
            $("#ultable").on("blur",".form-num",function(){
                $(this).parent('td').next('td').find('input').focus();
                plus();
            });
            $("#ultable").on("blur",".form-price",function(){
                plus();
            });
            function plus() {
                var nums = $('.form-num');
                var price = $('.form-price');

                //计算总数量
                var jn=0;
                var jp=0;
                for (var i=0;i<nums.length;i++){
                    jn+=parseInt(nums.eq(i).val());
                    var p = parseFloat(price.eq(i).val())==NaN ? 0 : parseFloat(price.eq(i).val());
                    jp+=parseFloat(p*parseInt(nums.eq(i).val()));
                    nums.eq(i).parent('td').next().next().html(parseFloat(p*parseInt(nums.eq(i).val())));
                }
                $("#tj1").html(jn);

                $("#tj2").html(parseFloat(jp).toFixed(2));

            }

            //前面数字排序
            function table_sort() {
                var trs = $("#ultable tr");
                if (trs.length==0)return;
                for (var i=1;i<=trs.length;i++){
                    trs.eq(i-1).find('td').eq(0).html(i);
                }


            }




            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});